package com.ryskoo.cms.advertpicrel.service;

import com.alibaba.fastjson.JSON;
import com.ryskoo.cms.advertpicrel.domain.AdvertPicRelPO;
import com.ryskoo.cms.advertpicrel.repository.IAdvertPicRelRepository;
import com.ryskoo.framework.core.exception.InvalidParamException;
import com.ryskoo.framework.core.service.BasicServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author thq
 * @data 2018-05-03
 */
@Service
public class AdvertPicRelServiceImpl extends BasicServiceImpl<AdvertPicRelPO> implements IAdvertPicRelService{
    @Autowired
    private IAdvertPicRelRepository advertRepository;

    @PostConstruct
    public void init(){
        this.setDao(advertRepository);
    }

    
	/**
	 * 保存广告关联的图片
	 * @param advertId
	 * @param pics
	 */
	@Override
	public void saveAdvertPicture(String advertId, String pics)
			throws InvalidParamException {
		
		//验证参数是否为空
		if (StringUtils.isEmpty(advertId) || StringUtils.isEmpty(pics)) {
			throw new InvalidParamException("无效的广告");
		}
		
		
		//先删除之前的广告图片
		advertRepository.deleteByAdvertId(advertId);
		
		if (!StringUtils.isEmpty(pics)) {
			List<Map<String, String>>  paramMap = (List<Map<String, String>>)JSON.parse(pics);
			
			if(null != paramMap) {
				if (paramMap.size() > 6) {
					throw new InvalidParamException("最多上传6张广告图");
				}
				
				//保存广告和图片关联关系
				List<AdvertPicRelPO> paramList = new ArrayList<AdvertPicRelPO>();
				for (Map<String, String> map : paramMap) {
					AdvertPicRelPO po = new AdvertPicRelPO();
					//设置广告Id
					po.setAdvertId(advertId);
					//设置图片url
					po.setUrl(map.get("url"));
					//设置图片外链
					po.setLink(map.get("link"));
					//设置图片排序
					try {
						po.setPosition(Integer.parseInt(map.get("position")));
					} catch (Exception e) {
						po.setPosition(0);
					}
					paramList.add(po);
				}
				
				//批量保存
				advertRepository.batchCreate(paramList);
			}
			
		}
	}
}
